﻿

#include "game.h"


HRESULT result;

CDirect3D *d3d;
CSprite *caveman1,*caveman2;
CSurface *back;
//CSounds *sound;
CInput *input;
CMusic *sound;


//timing variable
long start = GetTickCount();

//initializes the game
int Game_Init(HWND hwnd)
{
	d3d = new CDirect3D();
	if (!d3d->Init(hwnd, SCREEN_WIDTH, SCREEN_HEIGHT, FULLSCREEN))
        return 0;
		
	input = new CInput(hwnd);
	    
	sound=new CMusic();
	sound->InitSound(hwnd);
	//sound	= new CSounds(hwnd);
	//sound->addFile(STR_MP123_OGG_WAV_AIFF, "mysound", "s.wav", BASS_SAMPLE_MONO);

	//set random number seed
	srand(time(NULL));

    //load the background image
	back = new CSurface(d3d->GetDevice());
    back->Load("background.bmp", NULL);
	
	caveman1 = new CSprite(d3d->GetDevice(), "caveman.bmp",200,180,50,64,11,3);
	caveman2 = new CSprite(d3d->GetDevice(), "caveman.bmp",50,180,50,64,11,3);

    //return okay
    return 1;
}

//the main game loop
void Game_Run(HWND hwnd)
{
    //make sure the Direct3D device is valid
    if (d3d->GetDevice() == NULL)
        return;

	input->Update(hwnd);

	if(input->KeyPressed(DIK_RIGHT)) 
		sound->StopSound();
		//sound->play("mysound", true);

    //after short delay, ready for next frame?
    //this keeps the game running at a steady frame rate
    if (GetTickCount() - start >= 30)
    {
        //reset timing
        start = GetTickCount();
		
		caveman1->move(-5,0);
		caveman1->checkOutScreen();
		caveman1->animate();

		caveman2->move(5,0);
		caveman2->checkOutScreen();
		caveman2->animate();

    }

	if(caveman1->collide(caveman2))
		sound->LoopSound();

    //start rendering
    if (d3d->GetDevice()->BeginScene())
    {
        //erase the entire background
        d3d->GetDevice()->StretchRect(back->GetSurface(), NULL, d3d->GetBackBuffer(), NULL, D3DTEXF_NONE);
		
		caveman1->draw();
		caveman2->draw();
            
		//stop rendering
		d3d->GetDevice()->EndScene();
    }

    //display the back buffer on the screen
    d3d->GetDevice()->Present(NULL, NULL, NULL, NULL);

    //check for escape key (to exit program)
    if (KEY_DOWN(VK_ESCAPE))
        PostMessage(hwnd, WM_DESTROY, 0, 0);

}

//frees memory and cleans up before the game ends
void Game_End(HWND hwnd)
{
	d3d->Shutdown();
	delete caveman1;
	delete caveman2;
    delete back;    
	delete sound;
	delete input;
}

